const socketio = require('socket.io')
let io
let guestNumber = 1
let nickNames = {}
let namesUsed = []
let currentRoom = {}

exports.listen = function (server) {
  io = socketio.listen(server)
  io.set('log level', 1)
  io.sockets.on('connection', function (socket) {
    guestNumber = assignGuestName(socket, guestNumber, nickNames, namesUsed)
    joinRoom(socket, 'Lobby')

    handleMessageBroadcasting(socket, nickNames)
    handleNameChangeAttempts(socket, nickNames, namesUsed)
    handleRoomJoining(socket)

    socket.on('rooms', function () {
      socket.emit('rooms', io.sockets.manager.rooms)
    })

    handleClientDisconnection(socket, nickNames, namesUsed)
  })
}

// 设定默认用户名
function assignGuestName(socket, guestNumber, nickNames, namesUsed) {
  const name = 'Guest' + guestNumber
  nickNames[socket.id] = name
  socket.emit('nameResult', {
    success: true,
    name
  })
  namesUsed.push(name)
  return guestNumber + 1
}

// 加入聊天室
function joinRoom(socket, room) {
  console.log('joinRoom', room)
  socket.join(room)
  currentRoom[socket.id] = room
  socket.emit('joinResult', {room})
  socket.broadcast.to(room).emit('message', {
    text: nickNames[socket.id] + ' has joined ' + room + '.'
  })

  // 拼接当前聊天室网友信息
  const usersInRoom = io.sockets.clients(room)
  if (usersInRoom.length > 1) {
    let usersInRoomSummary = 'Users currently in ' + room + ': '
    for (const index in usersInRoom) {
      const userSocketId = usersInRoom[index].id
      if (userSocketId !== socket.id) {
        if (index > 0) {
          usersInRoomSummary += ', '
        }
        usersInRoomSummary += nickNames[userSocketId]
      }
    }
    usersInRoomSummary += '.'
    socket.emit('message', {text: usersInRoomSummary})
  }
}

// 处理更名请求
function handleNameChangeAttempts(socket, nickNames, namesUsed) {
  socket.on('nameAttempt', function (name) {
    console.log('nameAttempt', name)
    // 用户名不得以 Guest 开头
    if (name.indexOf('Guest') === 0) {
      socket.emit('nameResult', {
        success: false,
        message: 'Names cannot begin with "Guest".'
      })
      return
    }
    // 用户名不得重复
    if (namesUsed.indexOf(name) !== -1) {
      socket.emit('nameResult', {
        success: false,
        message: 'That name is already in use.'
      })
      return
    }

    // 更名
    const previousName = nickNames[socket.id]
    const previousNameIndex = namesUsed.indexOf(previousName)
    namesUsed.push(name)
    nickNames[socket.id] = name
    delete namesUsed[previousNameIndex]
    socket.emit('nameResult', {
      success: true,
      name
    })

    socket.broadcast.to(currentRoom[socket.id]).emit('message', {
      text: previousName + ' is now known as ' + name + '.'
    })
  })
}

// 消息广播
function handleMessageBroadcasting(socket) {
  socket.on('message', function (message) {
    console.log('message', message)
    socket.broadcast.to(message.room).emit('message', {
      text: nickNames[socket.id] + ': ' + message.text
    })
  })
}

// 加入房间
function handleRoomJoining(socket) {
  socket.on('join', function (room) {
    socket.leave(currentRoom[socket.id])
    joinRoom(socket, room.newRoom)
  })
}

function handleClientDisconnection(socket) {
  socket.on('disconnect', function () {
    const nameIndex = namesUsed.indexOf(nickNames[socket.id])
    delete namesUsed[nameIndex]
    delete nickNames[socket.id]
  })
}
